package com.tansun.easycare.rule.executionblock.web;

import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tansun.easycare.rule.common.enums.RuleModelTypeFileEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;
import com.tansun.easycare.core.utils.ResponseTable;
import com.tansun.easycare.rule.common.Constant;
import com.tansun.easycare.rule.common.ResMessage;
import com.tansun.easycare.rule.common.RuleBaseController;
import com.tansun.easycare.rule.common.model.ResponseVO;
import com.tansun.easycare.rule.common.model.SelectModelVo;
import com.tansun.easycare.rule.common.service.RuleCommService;
import com.tansun.easycare.rule.common.web.model.ProjectInfo;
import com.tansun.easycare.rule.datamodel.service.DataModelService;
import com.tansun.easycare.rule.exception.BizException;
import com.tansun.easycare.rule.executionblock.model.ExecutionBlockVO;
import com.tansun.easycare.rule.executionblock.service.ExecutionBlockService;
import com.tansun.easycare.rule.rulemange.entity.RuleManage;
import com.tansun.easycare.rule.rulemange.model.RuleManageVO;
import com.tansun.easycare.rule.rulemange.service.RuleManageService;
import com.tansun.rule.utils.LoggerManager;
import com.tansun.rule.utils.StringUtils;

@RestController
@RequestMapping(value = "/ruleProj/executionBlock")
public class ExecutionBlockController extends RuleBaseController {

    @Autowired
    private RuleManageService ruleManageService;
    @Autowired
    private ExecutionBlockService executionBlockService;
    @Autowired
    private RuleCommService ruleCommService;
    @Autowired
    private DataModelService dataModelService;
    /**
     * 执行块列表页面
     *
     * @param map ModelMap
     * @return JSP路径
     */
    @RequestMapping("index")
    public ResponseTable<RuleManageVO> index(@RequestBody RuleManageVO param) throws Exception {
        PageInfo<RuleManageVO> pageInfo = this.ruleManageService.findRuleManageVO(param.getPage(), param);
        ResponseTable<RuleManageVO>  resVo  = new  ResponseTable<RuleManageVO>(pageInfo);
        return resVo;
    }

    /**
     * 打开执行块新增页面
     *
     * @return JSP路径
     */
    @RequestMapping("toAdd")
    public String toAdd(ModelMap map) throws Exception {
        ExecutionBlockVO executionBlockVO = new ExecutionBlockVO();
        RuleManage ruleManage = new RuleManage();
        executionBlockVO.setRuleManage(ruleManage);
        ruleManage.setProjectCode(getCurrProjectCode());
        map.put("model", executionBlockVO);
        return "rule/executionblock/add";
    }
    /**
     * 添加规则集
     *
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     * @param rcv      规则集信息
     * @return 添加规则结果信息
     */
    @RequestMapping("addBlockCollectionVo")
    public @ResponseBody
    ResMessage addCollectionVo(HttpServletRequest request, HttpServletResponse response, @ModelAttribute RuleManage rcv) throws Exception {
        ResMessage res = new ResMessage("success", "添加成功");
        try {
            rcv.setModelType(rcv.getModelType());
            rcv.setProjectCode(this.getCurrProjectCode());
            rcv.setCountSalience(Constant.FIRST_SALIENCE);
            ruleManageService.saveOrUpdate(rcv);
            dataModelService.saveOrUpdateBuiltinParam(rcv.getCode(),rcv.getName(), rcv.getModelType(), rcv.getProjectCode(),rcv.getCreateBy());
        } catch (Exception e) {
            //e.printStackTrace();
            LoggerManager.error("", e, this.getClass());
            String msg = "操作失败！";
            if (e instanceof BizException) {
                BizException biz = (BizException) e;
                msg = biz.getMessage();
            }
            return new ResMessage("failure", msg);
        }
        return res;
    }

    /**
     * 打开执行块编辑页面
     *
     * @param code 执行块编码
     * @param map  ModelMap
     * @return JSP路径
     */
    @RequestMapping("toEdit")
    public ResponseVO toEdit(@RequestBody ProjectInfo projectInfo) throws Exception {
    	String id = projectInfo.getManageId();
        if (StringUtils.isEmpty(projectInfo.getManageId())) {
            throw new BizException("ID为空");
        }
        ResponseVO  res = new ResponseVO(); 
       	RuleManage ruleManage = ruleManageService.get(id);

        ExecutionBlockVO executionBlockVO = this.executionBlockService.findExecutionBlock(id,projectInfo.getProjectCode(), projectInfo.getVersion());
    
        executionBlockVO.setRuleManage(ruleManage);

       res.setData(executionBlockVO);
       return  res;
    }
    /**
     * 条件选择对话框
     *
     * @param projectCode 项目编码
     * @param context     节点数据
     * @param clickId     单击节点
     * @param map         ModelMap
     * @return String 页面地址
     */
    @RequestMapping("getConditionNodeInfo")
    public String getConditionNodeInfo(HttpServletRequest request, String projectCode, String context, String clickId, ModelMap map) throws Exception {
        //
        map.put("paramProjectCode", projectCode);
        map.put("paramData", context);
        map.put("paramTargeId", clickId);
        return "rule/executionblock/blockConditionTreeDlg";
    }

    @RequestMapping("getModelOptions")
    public ResponseVO getModelOptions(@RequestBody ProjectInfo projectInfo) throws Exception {
    	ResponseVO  res = new ResponseVO();
        List<SelectModelVo> list = this.ruleCommService.findSelectModelList(projectInfo.getProjectCode(), projectInfo.getModelType());
        res.setData(list);
        return  res;

    }


    @RequestMapping("getModelVersions")
    @ResponseBody
    public List<SelectModelVo> getModelVersions(String modelCode) throws Exception {
        if (StringUtils.isEmpty(modelCode)) {
            return Collections.emptyList();
        }
        return this.ruleCommService.findSelectPublishVersionList(getCurrProjectCode(), modelCode);

    }

    @RequestMapping("save")
    public ResponseVO save(@RequestBody ExecutionBlockVO executionBlockVO) throws BizException {
    	ResponseVO ret = new ResponseVO();
        try {
            Integer num = this.ruleManageService.countListFindName(executionBlockVO.getRuleManage(), executionBlockVO.getRuleManage().getModelType());
            if (num != null && num>0) {
                ret.setStatus(ResponseVO.ERROR);
                ret.setDescription("变量名称重复，请使用其他有效名称");
                return ret;
            }
//        	RuleManage rcv = executionBlockVO.getRuleManage();
//        	rcv.setModelType(RuleModelTypeEnum.ExecutionBlock.getCode());
//        	this.ruleManageService.save(rcv);
//        	RuleManage rm = this.ruleManageService.get(rcv.getId());
//            dataModelService.saveOrUpdateBuiltinParam(rm.getCode(),rcv.getName(), rm.getModelType(), rm.getProjectCode());
            this.executionBlockService.saveOrUpdate(executionBlockVO);
        } catch (Exception e) {
            LoggerManager.error("", e, this.getClass());
            ret.setStatus(ResponseVO.ERROR);
            ret.setDescription("状态修改失败，请查看日志");
        }
        return ret;
    }

    @Override
    public void setRuleBizService() {
        this.setRuleBaseService(executionBlockService);
    }


}
